/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.iuh.dhth7dlt.emailclient.ui;

import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import vn.edu.iuh.dhth7dlt.emailclient.utils.CheckInput;
import vn.edu.iuh.dhth7dlt.emailclient.utils.ConfigAccount;
import vn.edu.iuh.dhth7dlt.emailclient.utils.Consts;
import vn.edu.iuh.dhth7dlt.emailclient.utils.EmailAddress;
import vn.edu.iuh.dhth7dlt.emailclient.utils.EmailExceptions;
import vn.edu.iuh.dhth7dlt.emailclient.utils.Messenger;
import vn.edu.iuh.dhth7dlt.emailclient.utils.SMTP;

/**
 *
 * @author Administrator
 */
public class SendEmail extends javax.swing.JFrame {

    Consts c;
    CheckInput cki = null;
    public static ConfigAccount currentAccount;

    /**
     * Creates new form SendEmail
     */
    public SendEmail(ConfigAccount currentAccount) {
        initComponents();
        this.currentAccount = currentAccount;
        this.setLocationRelativeTo(null);//set center
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtxTo = new javax.swing.JTextField();
        jbtGuiThu = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxNoiDung = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jtxTieuDe = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jtxCc = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jtxBcc = new javax.swing.JTextField();
        jbtHuy = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 102, 255));
        jLabel1.setText("Soạn Thư");

        jLabel2.setText("Người Nhận");

        jbtGuiThu.setText("Gửi Thư");
        jbtGuiThu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtGuiThuActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 51, 255));
        jLabel3.setText("Nội dung");

        jtxNoiDung.setColumns(20);
        jtxNoiDung.setRows(5);
        jScrollPane1.setViewportView(jtxNoiDung);

        jLabel4.setText("Tiêu Đề");

        jLabel5.setText("Cc");

        jLabel6.setText("Bcc");

        jbtHuy.setText("Hủy");
        jbtHuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtHuyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbtGuiThu, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jbtHuy, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jtxBcc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
                            .addComponent(jtxCc, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxTo, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxTieuDe, javax.swing.GroupLayout.Alignment.LEADING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jtxTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jtxCc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel6))
                    .addComponent(jtxBcc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtxTieuDe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtHuy)
                    .addComponent(jbtGuiThu))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtHuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtHuyActionPerformed
        String message = "Bạn muốn hủy thực hiện này?";
        String title = "Thoát?";
        int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
            this.setVisible(false);
        }
    }//GEN-LAST:event_jbtHuyActionPerformed

    private void jbtGuiThuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtGuiThuActionPerformed
        try {
            //Kiểm tra mail nhập vào có hợp lệ không
            EmailAddress.getEmails(jtxTo.getText().trim());
        } catch (EmailExceptions ex) {
            Messenger.show(ex.get_error());
        }
//        cki = new CheckInput(c.EMAIL_PATTERN);
//        boolean valid = cki.validate(jtxTo.getText().toString().trim());
//        if (valid == false) {
//            Messenger.show("Nhập sai Email:example@gmail.com");
//            return;
//        }
        if ("".equals(jtxTieuDe.getText().trim())) {
            Messenger.show("Nhập tiêu đề thư gửi đi");
            return;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("body", jtxNoiDung.getText().toString());
        params.put("username", currentAccount.getUser());
        params.put("name", currentAccount.getName());
        params.put("pathDB", currentAccount.getPathDB());
        params.put("pass", currentAccount.getPassword());
        params.put("smtp", currentAccount.getSMTPserver());
        params.put("port", "" + currentAccount.getSMTPport());
        params.put("to", jtxTo.getText().trim());
        params.put("from", currentAccount.getEmail());
        params.put("cc", jtxCc.getText().trim());
        params.put("bcc", jtxBcc.getText().trim());
        params.put("subject", jtxTieuDe.getText().trim());

        if (params.get("to").isEmpty() || params.get("subject").isEmpty() || params.get("body").isEmpty()) {
            Messenger.show("bạn nhập thiếu thông tin.Hãy nhập lại!");
            return;
        }

        SMTP smtp = new SMTP();
        String response = null;
        try {
            response = smtp.sendmail(params);
        } catch (IOException ex) {
            Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
        } catch (EmailExceptions ex) {            
            Messenger.show(ex.get_error());
            response = ex.get_error();
        } finally {
            if(response.startsWith("250"))
            Messenger.show("Gửi Email thành công");
        }
    }//GEN-LAST:event_jbtGuiThuActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SendEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SendEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SendEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SendEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SendEmail(currentAccount).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtGuiThu;
    private javax.swing.JButton jbtHuy;
    private javax.swing.JTextField jtxBcc;
    public javax.swing.JTextField jtxCc;
    public javax.swing.JTextArea jtxNoiDung;
    public javax.swing.JTextField jtxTieuDe;
    public javax.swing.JTextField jtxTo;
    // End of variables declaration//GEN-END:variables
}
